/**
 * Created by zhu on 2016/2/13.
 */
$(function(){

    init_goods();

    $('#edit_confirm').on("click",function(){
        editGoods();
    });
    $('#delete_confirm').on("click",function(){
        deleteGoods();

    });
});

function init_goods(){
    $.get(contextPath+"/seller/goods",function(data){
        data = $.parseJSON(data);
        var goods = $('#tbody');
        goods.empty();
        $.each(data.list,function(i,item){
            var temp = ' <tr>'+
                '<td scope="row" style="vertical-align: middle;">' +
                '<img src="'+contextPath+item.index_url+'" style="height: 140px;width: 140px" class="img-thumbnail">'+
            '<p>'+item.name+'</p></td>'+
            '<td style="vertical-align: middle;font-size: 18px;">'+item.price+'</td>'+
            '<td style="vertical-align: middle;font-size: 18px;">'+item.goods_number+'</td>'+
            '<td style="vertical-align: middle;"><input type="hidden" id="myid" value="'+item.id+'">' +
               '<div class="btn-group btn-group-lg" role="group" aria-label="...">'+ '<button type="button" class="btn btn-info editBtn"  data-toggle="modal" data-target="#edit" >编辑</button>'+
            '<button type="button" class="btn btn-default deleteBtn">删除</button></td>'+'</div>'+
            '</tr>';
            goods.append(temp);
        });
        $('.editBtn').on("click",function(){
            $('#goodsId').val($($(this).parent().find("input")[0]).val());
            $('#price').val($($(this).parent().parent().find("td")[0]).text());
            $('#number').val($($(this).parent().parent().find("td")[1]).text());
            $('#name').val($($($(this).parent().parent().find("th")[0]).find("p")[0]).text());
        });
        $('.deleteBtn').on("click",function(){
            $('#deleteId').val($($(this).parent().find("input")[0]).val());
        });
    });
}

function editGoods(){
    $('#edit').modal('hide');
    $.post(contextPath+"/seller/goods",{goodsId:$('#goodsId').val(),
        price:$('#price').val(),
        number:$('#number').val(),
        name: $('#name').val()},function(data){
        if(data.status == 0){
            init_goods()
        }else{
            alert("修改失败");
        }
    },"json")
}

function deleteGoods(){
    $('#delete').modal('hide');
    var id = $('#deleteId').val();
    $.ajax({
        url: contextPath+'/seller/goods/'+id,
        type: 'DELETE',
        success: function(result) {
            init_goods()
        }
    });
}